Projection

In this tutorial, we will learn another interesting topic of MongoDB which is MongoDB Projection. This is used when we want to get the selected fields of the documents rather than all fields.For example, we have a collection where we have stored documents that have the fields: student_name, student_id, student_age but we want to see only the student_id of all the students then in that case we can use projection to get only the student_id.

Sysntax
db.collection_name.find({},{field_key:1 or 0})
db.collection_name.find({},{field_key:BOOLEAN})
  • collection_name is the name of the table from where you have to retrieve the record for processing.  
  • Field key is the name of the column or entity that you want to process from the table.
  • Boolean is the check to show and hide the column value.

 db.studentdata.find().pretty()
{
        "_id" : ObjectId("59bf63380be1d7770c3982af"),
        "student_name" : "Steve",
        "student_id" : 2002,
        "student_age" : 22
}
{
        "_id" : ObjectId("59bf63500be1d7770c3982b0"),
        "student_name" : "Carol",
        "student_id" : 2003,
        "student_age" : 22
}
{
        "_id" : ObjectId("59bf63650be1d7770c3982b1"),
        "student_name" : "Tim",
        "student_id" : 2004,
        "student_age" : 23
}

No comments:

Post a Comment